<?php
/***************************************************************************
 *
 *   copyright            : (C) 2011 Winds of Storm
 *
 *   $Id: chat_functs.php 131 2011-06-12 20:24:56Z stormerider $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

function getSid() {
	global	$db;
	global	$config;
	global	$dbprefix;

	srand((double)microtime()*1000000);
	
	$sid	= "";
	while ($sid == "") {
		$t_sid	= md5(rand());
		$sql	= "SELECT * FROM {$dbprefix}sessions WHERE session_id='$t_sid'";
		$result = $db->sql_query($sql);
		
		if (!$result) {
			//print("Error generating SID");
			//exit;
			$sid	= -1;
		}

		if (($row = $db->sql_fetchrow($result)) == NULL) {
			$sid	= $t_sid;
		}
	}

	return $sid;
}

function validAlias($alias, $uid) {
	global	$db;
	global	$dbprefix;

	//
	// Check to see if the alias is already registered to someone else... if so, it is not valid for use...
	//
	$sql	= "SELECT * FROM {$dbprefix}aliases WHERE user_alias LIKE '$alias' AND user_id != $uid";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return -1;
	}

	//
	// Check to see if the alias is someone else's username... if so, it is not valid for use...
	//
	$result	= checkValidAlias($alias, $uid);
	if ($result != 1) {
	//if ($result == -2) {
		//return -2;
		return $result;
	}

	//
	// Check to see if someone else is using this as a temporary alias... if so. it is not valid for use...
	//
	$sql	= "SELECT * FROM {$dbprefix}prefs WHERE user_alias LIKE '$alias' AND user_id != $uid";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return -3;
	}

	//
	// No problems with the previous checks... valid for use.
	//
	return 1;
}

function getRoomName($room_id) {
	global	$db;
	global	$config;
	global	$dbprefix;

	$sql	= "SELECT room_name FROM {$dbprefix}rooms WHERE room_id=$room_id";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row[0];
	}

	return "!!UNKNOWN!!";
}

function getOnlineUserIdByName($username) {
	global	$db;
	global	$config;
	global	$dbprefix;
	global	$user_name_field;
	global	$user_id_field;
	global	$users_table;
	
	$sql	= "SELECT user_id FROM {$dbprefix}sessions WHERE username LIKE '$username'";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		print("<!-- getOnlineUserIdByName($username) == {$row['user_id']} -->\n");
		print("<!-- SQL: $sql -->\n");
		return $row['user_id'];
	}

	$sql	= "SELECT s.user_id FROM {$dbprefix}sessions AS s,{$dbprefix}prefs AS p WHERE s.user_id=p.user_id AND user_alias LIKE '$username'";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		print("<!-- Alias: getOnlineUserIdByName($username) == {$row['user_id']} -->\n");
		print("<!-- SQL: $sql -->\n");
		return $row['user_id'];
	}

	return -1;
}

function getOnlineUserNameById($userid) {
	global	$db;
	global	$config;
	global	$dbprefix;
	
	$sql	= "SELECT username FROM {$dbprefix}sessions WHERE user_id=$userid";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row['username'];
	}

	return "[[- not found-]]";
}

function getUserAliasById($userid) {
	global	$db;
	global	$config;
	global	$dbprefix;
	
    if ($userid == -1) {
        return "[[chat server]]";
    }

	$sql	= "SELECT user_alias FROM {$dbprefix}prefs WHERE user_id=$userid";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row['user_alias'];
	}

	return "[[- not found-]]";
}
function getSessionPrefsById($userid) {
	global	$db;
	global	$config;
	global	$dbprefix;
	global	$user_name_field;
	global	$user_id_field;
	global	$users_table;
	
	$sql	= "SELECT * FROM {$dbprefix}sessions AS s,{$dbprefix}prefs AS p WHERE s.user_id=$userid AND s.user_id=p.user_id";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row;
	}

	return -1;
}

function checkUserRoomById($userid, $roomid) {
	global	$db;
	global	$config;
	global	$dbprefix;
	global	$user_name_field;
	global	$user_id_field;
	global	$users_table;
	
	$sql	= "SELECT * FROM {$dbprefix}sessions WHERE user_id=$userid AND room_id=$roomid";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return 1;
	}

	return -1;
}

function getSessionPrefsByName($username) {
	global	$db;
	global	$config;
	global	$dbprefix;
	global	$user_name_field;
	global	$user_id_field;
	global	$users_table;
	
	$sql	= "SELECT * FROM {$dbprefix}sessions AS s,{$dbprefix}prefs AS p WHERE s.username LIKE '$username' AND s.user_id=p.user_id";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row;
	}

	$sql	= "SELECT * FROM {$dbprefix}sessions AS s,{$dbprefix}prefs AS p WHERE p.user_alias LIKE '$username' AND s.user_id=p.user_id";
	$result = $db->sql_query($sql);
	if (($row = $db->sql_fetchrow($result)) != NULL) {
		return $row;
	}

	return -1;
}

function filter_msg($message) {
	global	$db;
	global	$config;
	global	$dbprefix;
	global	$plugins;
	global	$smilies_table;
	global	$smilies_path;
	global	$smile_pattern_field;
	global	$smile_url_field;
	global	$DISABLE_SMILIES;

	$msg	= $message;

	if (eregi("<a ", $msg)) {
		$msg	= eregi_replace("<a ", "<a target=_blank ", $msg);
	}

	if (eregi("url:", $msg)) {
		$msg	= eregi_replace("url:([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $msg);
	}

	if (eregi("img:", $msg)) {
		$msg	= eregi_replace("img:([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<img src=\"\\1://\\2\\3\">", $msg);
	}

	if (eregi("google:", $msg)) {
		$msg	= eregi_replace("google:([[:alnum:]]+)", "<a href=\"http://www.google.com/search?hl=en&q=\\1&btnG=Google+Search\" target=\"_blank\">Google: \\1</a>", $msg);
	}

	if (eregi("dictionary:", $msg)) {
		$msg	= eregi_replace("dictionary:([[:alnum:]]+)", "<a href=\"http://dictionary.reference.com/search?q=\\1\" target=\"_blank\">Dictionary.com: \\1</a>", $msg);
	}

	if (eregi("thesaurus:", $msg)) {
		$msg	= eregi_replace("thesaurus:([[:alnum:]]+)", "<a href=\"http://thesaurus.reference.com/search?q=\\1\" target=\"_blank\">Thesaurus.com: \\1</a>", $msg);
	}

	if (eregi("wiki:", $msg)) {
		$msg	= eregi_replace("wiki:([[:alnum:]]+)", "<a href=\"http://en.wikipedia.org/wiki/\\1\" target=\"_blank\">Wikipedia: \\1</a>", $msg);
	}

	if (eregi("ljuser:", $msg)) {
		$msg	= eregi_replace("ljuser:([[:alnum:]_]+)", "<a href=\"http://www.livejournal.com/userinfo.bml?user=\\1\" target=\"_blank\"><img src=\"http://stat.livejournal.com/img/userinfo.gif\" border=0></a> <a href=\"http://www.livejournal.com/users/\\1\" target=_blank>\\1</a>", $msg);
	}

	if (eregi("ljcomm:", $msg)) {
		$msg	= eregi_replace("ljcomm:([[:alnum:]_]+)", "<a href=\"http://www.livejournal.com/userinfo.bml?user=\\1\" target=\"_blank\"><img src=\"http://stat.livejournal.com/img/community.gif\" border=0></a> <a href=\"http://www.livejournal.com/community/\\1\" target=_blank>\\1</a>", $msg);
	}

	foreach ($plugins as $plugin) {
        if (($config[$plugin['FUNC']] == 'enabled') && (eregi("filter", $plugin['TYPE']))) {
			$msg	= call_user_func($plugin['FUNC'], $msg);
		}
	}

	$msg	= nl2br($msg);
	$msg	= ereg_replace("\n", "", $msg);
	$msg	= ereg_replace("\r", "", $msg);
	$msg	= addslashes($msg);

	if ($config['FORUM_TYPE'] != 'lj' ) {
		$sql	= "SELECT * FROM $smilies_table";
		$count	= 0;

		if ($result = $db->sql_query($sql)) {
			while ($sm_row = $db->sql_fetchrow($result)) {
				$count++;
 				$pattern	= $sm_row[$smile_pattern_field];
 				$pattern	= preg_quote($pattern);
 				$pattern	= ereg_replace("/", "\/", $pattern);

				$orig[] = "/(?<=.\W|\W.|^\W)" . $pattern . "(?=.\W|\W.|\W$)/";
				$repl[] = "<img src=\"{$smilies_path}{$sm_row[$smile_url_field]}\" alt=\"{$pattern}\" border=\"0\" />";
			}
		}

		if ($count > 0) {
			addToLog("Smilies: orig = ". print_r($orig, TRUE), -1, LOG_DEBUG);
			addToLog("Smilies: repl = ". print_r($repl, TRUE), -1, LOG_DEBUG);
			$msg	= preg_replace($orig, $repl, ' ' . $msg . ' ');
		}
		$msg	= substr($msg, 1, -1);
	}

	return $msg;
}

function getHelpCommands() {
	global	$plugins;
    global  $config;

	$help['away']		= array("/away", "First use, go away; second use, come back.");
	$help['alias1']		= array("/alias", "Remove your current alias.");
	$help['alias2']		= array("/alias [alias]", "Assume [alias] and change avatar if set (registered to you in database).");
	$help['me1']		= array("/me [msg]", "Emote command. (/me grins -> Alan Morgan grins)");
	$help['me2']		= array("/me 's [msg]", "Emote command with possesive attachment. (/me 's happy. -> Alan Morgan's happy.)");
	$help['msg1']		= array("/msg [user] [msg]", "Send [msg] to [user].");
	$help['msg2']		= array("/msg '[user]' [msg]", "Send [msg] to [user] (needed if [user] has spaces).");
	$help['msg3']		= array("/msg \"[user]\" [msg]", "Send [msg] to [user] (needed if [user] has spaces).");
	$help['noavatars']	= array("/noavatars", "Turn off avatar displaying for you.");
	$help['shout']		= array("/shout [msg]", "Send [msg] to all rooms (please use, don't abuse...).");
	$help['showavatars']	= array("/showavatars", "Turn avatar displaying back on for you.");
	$help['time']		= array("/time", "Show current time (handy for transcript queries)");
	$help['tagline1']	= array("/tagline", "Clears your current chat tagline.");
	$help['tagline2']	= array("/tagline [tagline]", "Changes your tagline to [tagline].");
	$help['tempalias1']	= array("/tempalias", "Remove your current alias.");
	$help['tempalias2']	= array("/tempalias [alias]", "Assume [alias] (not protected in database).");
	$help['kick1']		= array("/kick [user] [msg]", "Kick [user] from chat room (moderator only).");
	$help['kick2']		= array("/kick '[user]' [msg]", "Kick [user] from chat room (moderator only) (needed if [user] has spaces).");
	$help['kick3']		= array("/kick \"[user]\" [msg]", "Kick [user] from chat room (moderator only) (needed if [user] has spaces).");
	$help['wall']		= array("/wall [msg]", "Send [msg] notice to all rooms (moderator only).");
	$help['topic']		= array("/topic [topic]", "Sets the topic of the current room to [topic] (moderator only).");

	foreach($plugins as $plugin) {
		if (($config[$plugin['FUNC']] == 'enabled') && (eregi("command", $plugin['TYPE']))) {
			call_user_func_array($plugin['HELP'], array(&$help));
		}
	}
	ksort($help);

	return $help;
}

function getHelpFilters() {
	global	$plugins;
    global  $config;

	$help['ljcomm']		= array("ljcomm:[community]", "Show a chat-friendly link to the LiveJournal community [community].");
	$help['ljuser']		= array("ljuser:[user]", "Show a chat-friendly link to the LiveJournal user [user].");
	$help['wiki']		= array("wiki:[entry]", "Show a chat-friendly link to the WikiPedia entry for [entry]. (Note at this time it is for the English Wiki and [entry] can only be one word.)");
	$help['url']		= array("url:[someurl]", "Show a chat-friendly (link will not overwrite chat frame) link to [someurl].");
	$help['img']		= array("img:[imgurl]", "Display the image at [imgurl] in chat. (Please refrain from posting images that are inappropriate or may slow down other users. Use the url: filter instead.)");
	$help['google']		= array("google:[entry]", "Show a chat-friendly link to the Google entry for [entry]. (Note at this time [entry] can only be one word.)");
	$help['dictionary']	= array("dictionary:[entry]", "Show a chat-friendly link to the Dictionary.com entry for [entry]. (Note at this time [entry] can only be one word.)");
	$help['thesaurus']	= array("thesaurus:[entry]", "Show a chat-friendly link to the Thesaurus.com entry for [entry]. (Note at this time [entry] can only be one word.)");

	foreach($plugins as $plugin) {
		if (($config[$plugin['FUNC']] == 'enabled') && (eregi("filter", $plugin['TYPE']))) {
			call_user_func_array($plugin['HELP'], array(&$help));
		}
	}
	ksort($help);

	return $help;
}

function getHelp() {
	$help	= getHelpCommands();
	foreach ($help as $this_help) {
		$msg	.=	"<tr><td NOWRAP valign=top><b>" . $this_help[0] . "</b></td><td>" . $this_help[1] . "</td></tr>";
	}

	return $msg;
}

function pluginCredit($plugin) {
	return "<br /><b>[" . $plugin['NAME'] . " plugin by " . $plugin['CREDIT'] . "]</a>";
}

function addToLog($msg, $uid = -1, $msg_level = LOG_WARN) {
	global	$db;
	global	$dbprefix;
    global  $DEBUG;
    global  $config;

    $log_level  = LOG_ERR;

    if (isset($config['DEBUG'])) {
        $log_level  = $config['DEBUG'];
    } else if (isset($DEBUG)) {
        $log_level  = $DEBUG;
    }

    if ($log_level >= $msg_level) {
	    $msg	= addslashes($msg);
        $trace  = addslashes(print_r(debug_backtrace(), TRUE));
	    $sql	= "INSERT INTO {$dbprefix}logs (log_userid, log_date, log_msg, log_trace) VALUES ($uid, NOW(), '$msg', '$trace')";
	    $db->sql_query($sql);
    }
}

function checkBan($uid) {
	global	$db;
	global	$dbprefix;

	addToLog("checkBan initializing...", $uid, LOG_DEBUG);

	$sql	= "SELECT * FROM {$dbprefix}bans WHERE ban_type='userid' AND ban_value='$uid'";
	$res	= $db->sql_query($sql);
	$rows	= $db->sql_numrows($res);
	addToLog("checkBan: $sql matched $rows rows", $uid, LOG_INFO);

	if ($rows != 0) {
		return 1;
	}

	$sql	= "SELECT * FROM {$dbprefix}bans WHERE ban_type='ip' AND ban_value='{$_SERVER['REMOTE_ADDR']}'";
	$res	= $db->sql_query($sql);
	$rows	= $db->sql_numrows($res);
	addToLog("checkBan: $sql matched $rows rows", $uid, LOG_INFO);

	if ($rows != 0) {
		return 1;
	}

	return 0;
}

function showFatalError($msg, $header = "Fatal Error") {
	global	$config;
	global	$full_header;
	global	$body;

	if (!defined('HEADER_LOADED')) {
		//$full_header	= 0;
		showHeader($body);
	}

	$template = new Template($config['TPL_DIR']);
	$template->set_filenames(array('error' => 'error_body.tpl'));

	$template->assign_vars(array(
		'ERROR'		=> $msg,
		'HEADER'	=> $header
	));

	$template->pparse('error');

	exit;
}

function setDomainText($fname, $header, $cpsp) {
	global  $config;
	global  $DEBUG;
	
	if ($cpsp == MODE_SERVER_PUSH && $config['DOMAIN']) {
		$hdr    = "<script>\n";
		if ($DEBUG) {
			$hdr	.= "\tvar test = document.domain;\n";
		}
		$hdr    .= "\tdocument.domain='{$config['DOMAIN']}';\n";
		if ($DEBUG) {
			$hdr	.= "\talert('$fname:\\nold domain = ' + test + '\\nnew domain = ' + document.domain);\n";
		}
		$hdr    .= "</script>\n";
		
		$header[]['HEADER_TEXT']        = $hdr;
	}
}

function getBaseURI() {
    $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
    $uri = $protocol.'://'.$_SERVER['HTTP_HOST'].preg_replace('/(.*)\/(.*?).php/', '${1}/', $_SERVER['SCRIPT_NAME']);
    return $uri;
}

function set_config($name, $value) {
    global  $config;
    global  $db2;
    global  $dbprefix;

    if (isset($config[$name])) {
        addToLog("set_config: Changing $name to $value", -1, LOG_INFO);
        $sql    = "UPDATE {$dbprefix}config SET config_value='$value' WHERE config_name='$name'";
    } else {
        addToLog("set_config: Setting $name to $value", -1, LOG_INFO);
        $sql    = "INSERT INTO {$dbprefix}config (config_name, config_value) VALUES ('$name', '$value')";
    }
    $res    = $db2->sql_query($sql);

    //
    // Make change take effect right now... don't wait for next page load and init to reparse config.
    //
    $config[$name]  = $value;

    return $res;
}

function print_r_pre($x) {
    print("<pre>\n");
    print_r($x);
    print("\n</pre>\n");
}

function print_sql_comment($sql) {
    $str_sql = ereg_replace("\n", " ", $sql);
    $str_sql = ereg_replace("\t", "", $str_sql);
    for ($i = 0; $i < 11; $i++) {
        $str_sql = ereg_replace("  ", " ", $str_sql);
    }
    print("<!-- SQL: $str_sql -->\n");
}

//
// Load plugins...
//
if (function_exists('scandir')) {
	$plugin_files   = @scandir($plugindir);
} else {
	$dh  = opendir($plugindir);
	while (false !== ($filename = readdir($dh))) {
		$plugin_files[] = $filename;
	}

	sort($plugin_files);
}

if (is_array($plugin_files)) {
	$plugins    = array();
    $count      = 0;

	foreach ($plugin_files as $key => $plugin) {
        if (eregi('.' . $phpEx . '$', $plugin)) {
            include_once("$plugindir/$plugin");
            $func   = $plugins[$count]['FUNC'];
            if (!isset($config[$func])) {
                $sql    = "INSERT INTO {$dbprefix}config (config_name, config_value) VALUES ('$func', 'enabled')";
                $res    = $db2->sql_query($sql);

                $config[$func]  = 'enabled';
            }
            $plugins[$count]['ENABLED'] = $config[$func];
            $count++;
        }
	}
}
